package com.lanou3g.ssm.service.impl;

import com.lanou3g.ssm.bean.Book;
import com.lanou3g.ssm.bean.BookExample;
import com.lanou3g.ssm.bean.LayUITableData;
import com.lanou3g.ssm.mapper.BookMapper;
import com.lanou3g.ssm.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class BookServiceImpl implements BookService {

    private List<Book> bookCache = null;

    @Autowired
    private BookMapper bookMapper;

    @Override
    public List<Book> queryBooks(Book condition) {
        BookExample bookExample = new BookExample();
        BookExample.Criteria criteria = bookExample.createCriteria();
        if(condition != null) {
            if(condition.getBookName() != null) {
                criteria.andBookNameLike(condition.getBookName());
            }
            if(condition.getAuthor() != null) {
                criteria.andAuthorEqualTo(condition.getAuthor());
            }
        }
        return bookMapper.selectByExample(bookExample);
    }

    @Override
    public LayUITableData<Book> queryBooksForLayUI(Book condition, Integer pageSize, Integer currentPage) {

        if(bookCache == null) {
            bookCache = queryBooks(null);
        }

        int startIdx = (currentPage - 1) * pageSize;
        int endIdx = currentPage * pageSize;
        if(endIdx > bookCache.size()) {
            endIdx = bookCache.size();
        }

        List<Book> currentPageData = bookCache.subList(startIdx, endIdx);

        LayUITableData<Book> retData = new LayUITableData();
        retData.setCode(0);
        retData.setCount((long)(bookCache.size()));
        retData.setMsg("查询成功");
        retData.setData(currentPageData);
        return retData;
    }
}
